import {
  Table,
  Form,
  Spin,
  DatePicker,
  Space,
  Switch,
  Input,
  Button,
  Image,
  message,
  Modal,
} from 'antd';
import * as api from '@/api/product';
import { ReactNode, useEffect, useRef, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import {
  EyeOutlined,
  SearchOutlined,
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
} from '@ant-design/icons';
import './index.css';
// import product from "@/models/product";
import MyModal from '@/components/myModal';
import type { TableRowSelection } from 'antd/es/table/interface';

interface DataType {
  product_id: string;
  productName: string;
  price: number;
  imageUrl?: string;
  description?: string;
  inventory?: number;
  category_id?: string;
  _id?: string;
  operation: ReactNode;
  name?: string;
}

{
  /* <ww>
    <input type="text" name="" id="" />
</ww> */
}

const rowSelection: TableRowSelection<DataType> = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      'selectedRows: ',
      selectedRows,
    );
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
  },
};

const ProductList = () => {
  // 家在东安湖
  let [tableLoading, setTableLoading] = useState<boolean>(false);
  // 表格数据
  let [data, setData] = useState<DataType[]>([]);
  // 模态框是否显示的属性
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 对话框的标题
  let [title, setTitle] = useState<string>('添加商品');
  // 修改时请求的商品id
  const [productId, setProductId] = useState<string>('');
  // 删除时打开的模态框
  const [ModalOpen, setModalOpen] = useState<boolean>(false);
  // 存储删除时的product_id
  const [delId, setDelId] = useState<string>('');
  // 是否上架
  const [checkStrictly, setCheckStrictly] = useState(false);

  //封装list函数
  let getList = async () => {
    // 打开加载动画
    setTableLoading(true);
    let res = await api.getProductApi();
    console.log(res);
    setData(res.data.data);
    res.data.data.forEach((item: any) => {
      item.key = Math.random().toString(32).substring(2);
    });

    // 关闭加载动画
    setTableLoading(false);
  };

  // 获取列表数据
  useEffect(() => {
    // console.log(bb);

    getList();
  }, []);

  // 注册表头数据
  let columns: ColumnsType<DataType> = [
    {
      key: '1',
      title: '产品图片',
      dataIndex: 'imageUrl',
      align: 'center',
      render(row) {
        // console.log(row)
        return (
          <Image
            // width={200}
            src={
              row
                ? row
                : 'https://img2.baidu.com/it/u=2421090168,324781765&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1673110800&t=25e086e66b814c4966b8ae843e6586c6'
            }
          />
        );
      },
    },
    {
      key: '2',
      title: '产品编号',
      dataIndex: 'product_id',
      align: 'center',
    },
    {
      key: '3',
      title: '产品名称',
      dataIndex: 'productName',
      align: 'center',
    },
    {
      key: '4',
      title: '价格',
      dataIndex: 'price',
      align: 'center',
    },
    {
      key: '5',
      title: '描述',
      dataIndex: 'description',
      align: 'center',
    },
    {
      title: '是否上架',
      align: 'center',
      render() {
        return (
          <Space align="center" style={{ marginBottom: 16 }}>
            <Switch checked={checkStrictly} onChange={setCheckStrictly} />
          </Space>
        );
      },
    },
    {
      key: '6',
      title: '库存',
      dataIndex: 'inventory',
      align: 'center',
      defaultSortOrder: 'descend',
      sorter: (a, b) => a.inventory! - b.inventory!,
    },
    {
      key: '7',
      title: '操作',
      dataIndex: 'operation',
      align: 'center',
      render(row, record) {
        return (
          <div className="action_button">
            <Button
              type="primary"
              icon={<EyeOutlined />}
              style={{ backgroundColor: '#32CD32', borderColor: '#32CD32' }}
            />
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={updateProduct(record)}
            />
            <Button
              type="primary"
              icon={<DeleteOutlined />}
              danger
              onClick={delProduct(record)}
            />
          </div>
        );
      },
    },
  ];

  // 打开模态框的方法
  const showModal = () => {
    setIsModalOpen(true);
    // 修改标题
    setTitle('添加商品');
  };

  // 点击模态框中的确定按钮
  // const handleOk = async () => {
  //     let res = null

  //     if(title==='添加商品'){
  //         let obj = {
  //             category_id:'20230110135759644',
  //             productName:name,
  //             price:price,
  //             description:description,
  //             inventory:inventory,
  //             imageUrl:imageUrl
  //         }

  //         try{
  //             res = await api.addProduct(obj)
  //             // console.log(res)
  //         }catch(e){
  //             console.log(e)
  //         }
  //     }else{
  //         let obj = {
  //             category_id:category_id,
  //             product_id:product_id
  //         }
  //         try{
  //             res = await api.updateProduct(obj)
  //         }catch(e){
  //             console.log(e)
  //         }
  //     }
  //     // console.log(res)
  //     if(res!.data.state){
  //         // 清空列表
  //         setDescription('')
  //         setImageUrl('')
  //         setInventory('')
  //         setName('')
  //         setPrice('')
  //         // 关闭模态框
  //         setIsModalOpen(false)
  //         // 更新列表
  //         getList()
  //         // 成功提示框
  //         message.open({
  //             type:'success',
  //             content:`${title}成功`
  //         })
  //     }else{
  //         // 失败提示框
  //         message.open({
  //             type:"error",
  //             content:`${title}失败`
  //         })
  //     }
  // };

  // 点击模态框中的取消按钮
  // const handleCancel = () => {
  //     setIsModalOpen(false);

  // };

  // 删除商品
  let delProduct = (record: any) => () => {
    // 打开模态框
    setModalOpen(true);
    // 存储产品的id
    setDelId(record.product_id);
  };

  // 删除打开的模态框
  // 确定按钮
  const handleOkk = async () => {
    try {
      let res = await api.delProduct(delId);
      if (res.data.state) {
        // 更新列表
        getList();
        // 关闭模态框
        setModalOpen(false);
        // 删除成功提示
        message.open({
          type: 'success',
          content: '删除成功',
        });
      }
    } catch (e) {
      // 删除失败提示
      message.open({
        type: 'error',
        content: '删除失败',
      });
    }
  };

  // 取消按钮
  const handleCancell = () => {
    // 关闭模态框
    setModalOpen(false);
    // 取消删除提示框
    message.open({
      type: 'warning',
      content: '已取消删除',
    });
  };

  // 修改商品
  let updateProduct = (record: any) => () => {
    // console.log(bb);
    // console.log(record)
    // 打开模态框
    setIsModalOpen(true);
    // 修改标题
    setTitle('修改商品');
    // 回显数据
    bb.current.aaa({
      category_id: record.category_id,
      productName: record.productName,
      price: record.price,
      description: record.description,
      inventory: record.inventory,
    });
    // 回显图片
    bb.current.bbb(record.imageUrl);
    // 传递商品id
    setProductId(record.product_id);
  };

  // 批量删除数据
  let Deletion = () => {};

  // 获取子组件暴露来的方法
  let bb = useRef<any>(null);

  return (
    <div className="productList">
      <MyModal
        ref={bb}
        getList={getList}
        title={title}
        productId={productId}
        isModalOpen={isModalOpen}
        setIsModalOpen={setIsModalOpen}
      ></MyModal>
      <div className="tip">
        <p className="tip_top">操作提示</p>
        <ul>
          <li>1.该页展示了商城所有的商品信息,可对商品进行修改操作</li>
          <li>2.商家添加商品后,需要耍新页面才能看到最新商品</li>
        </ul>
      </div>
      <div className="operation">
        <div className="button">
          <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
            添加商品
          </Button>
          <Button
            type="primary"
            icon={<DeleteOutlined />}
            danger
            onClick={Deletion}
          >
            批量删除
          </Button>
        </div>
        <Modal
          title="删除提示"
          open={ModalOpen}
          okText="确定"
          cancelText="取消"
          onOk={handleOkk}
          onCancel={handleCancell}
        >
          <p>确定删除这条数据吗？</p>
        </Modal>
        <div className="search">
          <Form
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
            initialValues={{ remember: true }}
          >
            <Form.Item label="商品内容">
              <Input />
            </Form.Item>
            <Form.Item label="添加时间">
              <DatePicker />
            </Form.Item>
          </Form>
          <Button type="primary" icon={<SearchOutlined />}>
            查询
          </Button>
        </div>
      </div>
      <Spin spinning={tableLoading}>
        <Table
          rowSelection={{ ...rowSelection, checkStrictly }}
          dataSource={data}
          columns={columns}
          scroll={{ y: 270 }}
          pagination={{ position: ['bottomLeft'], pageSize: 10 }}
        />
      </Spin>
    </div>
  );
  // columns={columns} dataSource={data}
};

export default ProductList;
